<template>
  <div class="security-intelligent-page">
    <div class="breadcrumb">
      <Breadcrumb :data="breadcrumbData"></Breadcrumb>
    </div>
    <main>
      <div class="search-content">
        <div class="serach-item">
          <el-input
            v-model="searchAddress"
            placeholder="请输入地址"
            @keydown.native.enter="handleSearch">
          </el-input>
          <el-button type="primary" @click="handleSearch">
            <i class="el-icon-search"></i>
          </el-button>
        </div>
<!--        <div class="search-select">-->
<!--          <el-switch-->
<!--            class="condition"-->
<!--            v-model="value1"-->
<!--            active-text="火情监测点">-->
<!--          </el-switch>-->
<!--          <el-switch-->
<!--            class="condition"-->
<!--            v-model="value2"-->
<!--            active-text="有毒有害气体检测点">-->
<!--          </el-switch>-->
<!--          <el-switch-->
<!--            class="condition"-->
<!--            v-model="value3"-->
<!--            active-text="监控">-->
<!--          </el-switch>-->
<!--        </div>-->
      </div>
      <div class="map-container">
        <div class="btn-wrap" style="top:100px;right:10px;width:80px;height:180px;">
<!--          <el-button type="primary" @click="handleSelect">线段设置</el-button>-->
<!--          <el-button type="primary" @click="handleCircle">圆形设置</el-button>-->
<!--          <el-button type="primary" @click="handleClear">删除分区</el-button>-->
<!--          <el-button type="primary" @click="handleClearMap">清空地图</el-button>-->
        </div>
        <div id="security-intelligent-map"></div>
      </div>
    </main>
  </div>
</template>

<script>
import Breadcrumb from '@/components/public/Breadcrumb';
import excavatingMachinery from '@/assets/images/car/excavating_machinery.png';
import pilingMachine from '@/assets/images/car/piling_machine.png';
import truckMountedCrane from '@/assets/images/car/truck_mounted_crane.png';
import longExcavatingMachinery from '@/assets/images/car/long_excavating_machinery.png';
import car from '@/assets/images/car/car.png';
import forklift from '@/assets/images/car/forklift.png';
import crane from '@/assets/images/car/crane.png';

export default {
  data() {
    return {
      // 面包屑数据
      breadcrumbData: [
        {
          name: '安全管理',
        },
        {
          name: '智慧化安全管理'
        }
      ],
      // 刷新车辆定位定时器
      timer: null,
      // 定位器id
      locatorId: '',
      // 车俩定位信息
      locationList: [],
      // 轨迹实例
      polyline: null,
      carTrackList: [],
      searchAddress: '',
      value1: false,
      value2: false,
      value3: false,
      // 打卡信息
      clockList: [],
      // 地图实例
      mapApp: null,
      // 地址解析器的实例
      geocoder: null,
      // 地图标注对象
      marker: null,
      // 当前标签对象
      labelApp: null,
      btnLoading: false
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    },
    // 打卡标注信息
    clockMarkerList() {
      /* eslint-disable */
        const result = [];
        this.locationList.forEach(item => {
          const { jing_du, wei_du, name } = item;
          if (!jing_du || !wei_du) return;
          const point = new T.LngLat(Number(jing_du), Number(wei_du));
          console.log('item', item);
          let iconUrl = '';
          if (/挖机/g.test(name)) iconUrl = excavatingMachinery;
          else if (/打桩/g.test(name)) iconUrl = pilingMachine;
          else if (/铲车/g.test(name)) iconUrl = forklift;
          else if (/长臂挖机/g.test(name)) iconUrl = longExcavatingMachinery;
          else if (/随车吊/g.test(name)) iconUrl = truckMountedCrane;
          else if (/起重机/g.test(name)) iconUrl = crane;
          else iconUrl = car;
          const icon = new T.Icon({
            iconUrl,
            iconSize: new T.Point(40, 40),
            // iconAnchor: new T.Point(10, 25)
          });
          const marker = new T.Marker(point, {
            icon,
            title: name,
            itemData: item
          });
          result.push({
            point,
            marker
          });  // 创建标注
          marker.addEventListener('click', this.handleMarkerClick)
        });
        return result;
      }
    },
    mounted() {
      this.getVehicleLocatorList(true);
      this.initMap();
    },
    beforeDestroy() {
      this.timer && clearTimeout(this.timer);
    },
    components: {
      Breadcrumb
    },
    methods: {
      // 地图初始化 120.16498, 30.28509
      initMap() {
        /* eslint-disable */
        const zoom = 14;
        const mapOptions = {
          datasourcesControl: true
        };
        this.mapApp = new T.Map('security-intelligent-map', mapOptions);
        this.mapApp.centerAndZoom(new T.LngLat(116.40969, 39.89945), zoom);
        this.geocoder = new T.Geocoder();
        this.ctrl = new T.Control.MapType();
        this.mapApp.addControl(this.ctrl);
      },
      // 清除地图标记
      clear() {
        this.mapApp && this.mapApp.clearOverLays();
      },
      // 定时获取定位数据
      getDataToTimer() {
        this.timer && clearTimeout(this.timer);
        this.timer = setTimeout(this.getVehicleLocatorList, 10000);
      },
      /**
       * 标注的点击事件
       */
      handleMarkerClick(e) {
        const { lnglat, target: { options: { itemData }}} = e;
        const contentStr = `<div style="background: #232350; color: #bac4ff;">
                            <p style="text-align: center;">详细信息</p>
                            <div style="line-height: 25px;">定位器名称：${itemData.name || ''}</div>
                            <div style="line-height: 25px;">定位器类型：${itemData.type || ''}</div>
                            <div style="line-height: 25px;">电量：${itemData.electricity || ''}</div>
                            <div style="line-height: 25px;">绑定车辆名称 ：${itemData.name_bind || ''}</div>
                          </div>`;
        const infoWin = new T.InfoWindow();
        infoWin.setContent(contentStr);
        this.mapApp.openInfoWindow(infoWin, lnglat);
        this.locatorId = itemData.id;
        this.getHisLocatorById(itemData.id)
      },
      /**
       * 地址搜索
       */
      handleSearch() {
        /* eslint-disable */
        if (!this.geocoder) return;
        const hasAddress = /^(\s+)$/g.test(this.searchAddress);
        if (hasAddress) {
          this.mapApp.panTo(new T.LngLat(116.40969, 39.89945), 14);
          return;
        }
        this.geocoder.getPoint(this.searchAddress, (res) => {
          if (res.getStatus() === 0) {
            const point = res.getLocationPoint();
            this.mapApp.panTo(point, 14);
            this.marker && this.mapApp.removeOverLay(this.marker);
            // 创建标注对象
            this.marker = new T.Marker(point);
            // 向地图上添加标注
            this.mapApp.addOverLay(this.marker);
            return;
          }
          this.$message.warning(res.getMsg() || '地址解析异常');
        });
      },
      /**
       * 设置标记点
       * @param {?Boolean} hasShow true: 展示
       * @param {?Boolean} hasPanto 是否到视图中心
       */
      setMarker(hasShow = false, hasPanto) {
        this.clockMarkerList.forEach(({ marker, point }, index) => {
          if (hasShow) {
            this.mapApp.addOverLay(marker);
            hasPanto && index === 0 && this.mapApp.panTo(point, 8);
            return;
          }
          this.mapApp.removeOverLay(marker);
        });
      },
      /**
       * 设置当前定位点车辆的历史轨迹
       * @param {Array} list 轨迹坐标
       */
      setCatTrack(list) {
        this.polyline && this.mapApp.removeOverLay(this.polyline);
        this.carTrackList = list
          .filter((item) => item.jing_du && item.wei_du)
          .map(item => {
            const { jing_du, wei_du } = item;
            return new T.LngLat(Number(jing_du), Number(wei_du));
          });
        this.polyline = new T.Polyline(this.carTrackList);
        this.mapApp.addOverLay(this.polyline);
      },
      /**
       * 根据定位器id获取当前定位器的历史轨迹
       * @param {?String} id 定位器id
       */
      async getHisLocatorById(id) {
        const { success, data: { data }} = await this.$Model.getHisLocatorById({
          locatorId: id || this.locatorId
        });
        if (success && Array.isArray(data)) {
          this.setCatTrack(data);
        }
      },
      /**
       * 获取车辆定位数据
       * @param {Boolean} hasPanto
       */
      async getVehicleLocatorList(hasPanto) {
        const { success, data: { data }} = await this.$Model.getVehicleLocatorList({
          projectId: this.projectId
        });
        if (success && Array.isArray(data)) {
          this.locationList = data;
          this.setMarker(false);
          this.setMarker(true, hasPanto);
        }
        // this.getDataToTimer();
      }
    }
  };
</script>

<style scoped lang="scss">
  @import '../../../assets/styles/table';
  @import '../../../assets/styles/dialog';

  .security-intelligent-page {
    width: 100%;
    height: 100%;
    background-color: $baseBg;
    color: #fff;
    main {
      width: 100%;
      height: calc(100% - 40px);
      padding: 20px;
      border-radius: 10px;
      .search-content {
        width: 100%;
        height: 80px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 20px;
        .serach-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          .el-input {
            width: 240px;
          }
          .el-button {
            margin-left: 20px;
          }
        }
        .condition {
          margin-left: 30px;
          /deep/ .el-switch__label {
            color: #fff;
          }
        }
      }
      .map-container {
        width: 100%;
        height: calc(100% - 80px);
        position: relative;
        #security-intelligent-map {
          width: 100%;
          height: 100%;
        }
      }
      .btn-wrap {
        width: 80px;
        height: 240px;
        position: absolute;
        top: 100px;
        right: 10px;
        z-index: 999;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-around;
        /deep/ .el-button {
          width: 100%;
          margin: 0;
          font-size: 12px;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }
  }
  .intelligent-set-map-model {
    .content {
      height: 120px;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      .item {
        width: 100%;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        .el-input {
          width: 300px;
        }
        .label {
          width: 120px;
          text-align: center;
        }
      }
    }
  }
</style>
